<?php

namespace app\apiadmin\service\liveManager;

use app\apiadmin\model\action\ActionModel;
use app\apiadmin\service\statics\LiveUserGetDataService;
use app\apiadmin\service\statics\MongoDbService;
use app\common\utils\Res;
use Predis\Client;
use think\facade\Db;
use think\facade\Log;

class LiveOnlineService
{

    /**  @var Client redis */
    private $redis;
    /** @var MongoDbService */
    private $_mongodb;
    /**
     * 直播管理
     */
    public function __construct($config = [], Client $redis = null)
    {
        $this->redis = $redis;
    }
    public static function salerList($param)
    {
        $salerList = DB::table('xh_zhujiao_group_list')->alias('z')
                        ->leftJoin(['xh_qw_sync_user'=> 'q'], 'z.userid = q.userid')
                        ->where(array('z.del' => 0))->field('z.id,z.userid,q.name')
                        ->select();
        $data = [
            'list' => $salerList,
            'total' => count($salerList),
        ];
        return Res::ok($data);
    }
    //获取所有在线用户 离线用户
    public static function getLineUser($param){
        //print_r($param);exit;
        $map = [];
        if(!$param['live_id']){
            return Res::error('直播信息不存在');
        }
        if(!in_array($param['online_status'],[0,1])){
            return Res::error('参数类型错误');
        }
       if($param['userid']){
           $arr_wx_unionid = Db::table('xh_siyu_invitation_user')
               ->where('liveId',$param['live_id'])
               ->where('sender',$param['userid'])
               ->column('wx_unionid');
           if(!$arr_wx_unionid){
              return Res::ok(['list'=>[],'total'=>0]);
           }
           $map['wx_unionid'] = ['$in'=>$arr_wx_unionid];
       }
        $map['online_status'] = "".$param['online_status'];
        //查询用户信息
        $param['pageNumber'] = !isset($param['pageNumber']) ? 1: (int) $param['pageNumber'];
        $limit = !isset($param['pageSize']) ? 100 : (int) $param['pageSize'];
        $offset = ($param['pageNumber'] - 1) * $limit;
        $findName = [];
        $collection = 'live_user_'.$param['live_id'];
        $result = ActionModel::pageMap_pinglun($collection,$map, $findName, $offset, $limit);
        if($result){
            
            $search_wx_unionid = [];
            foreach ($result as $key=>&$value){
                if(isset($value->wx_unionid) && $value->wx_unionid){
                    $search_wx_unionid[] = $value->wx_unionid;
                }
            }
            $salerList = [];
            if($search_wx_unionid){
                $salerList = DB::table('xh_siyu_invitation_user')->alias('s')
                    ->leftJoin(['xh_qw_sync_user'=> 'q'], 's.sender = q.userid')
                    ->whereIn('s.wx_unionid',$search_wx_unionid)
                    ->column('q.name','s.wx_unionid');
            }
            
            foreach ($result as $key=>&$value){
                $value->saler_name = '';
                if(isset($value->wx_unionid) && $value->wx_unionid){
                    if(isset($salerList[$value->wx_unionid])) $value->saler_name = $salerList[$value->wx_unionid];
                }
            }
        }
        $total = ActionModel::pageMapCount_pinglun($collection,$map);
        $data = [
            'list' => $result,
            'total' => $total,
        ];
        return Res::ok($data);

    }
    public static function isUserSaler($param,$userName){
        $isSaler = Db::table('xh_zhujiao_group_list')->where('userid',$userName)->field('userid')->find();
        if($isSaler){
            $isOk = true;
        }else{
            $isOk = false;
        }
        $data = [
            'isOk' => $isOk,
            'userid' =>$userName,
        ];
        return Res::ok($data);
    }
    //获取销售邀请用户id列表
    public static function getSalerInvatationUserIds($param,$userName){
        $map = [];
        if(empty($param['userid'])){
            return  Res::error('参数不正确');
        }
        if(!empty($param['liveId'])){
            $map['s.liveId'] = $param['liveId'];
        }
        if($param['userid']=='other'){
        }else{
            $map['s.sender'] = $param['userid'];
        }
        $userIdList = DB::table('xh_siyu_user')->alias('u')
            ->leftJoin(['xh_siyu_invitation_user'=> 's'], 's.wx_unionid = u.unionid')
            ->leftJoin(['xh_qw_sync_user'=> 'q'], 's.sender = q.userid');
        if($map) $userIdList->where($map);
        $userList = $userIdList->field('u.id,q.name,q.userid as saler_userid')->group('u.id')->select()->toArray();
        
        $userIdList = array_column($userList,'id');
        $userIdNameList = array_column($userList,'name','id');
        //$userIdSalerUserIdList = array_column($userList,'saler_userid','id');
        $data = [
            'list' => $userIdList,
            'userIdSalerUserIdList' =>$userIdNameList,
        ];
        return Res::ok($data);
    }
    //获取评论列表
    public static function getPinglunList($param){
            $map = [];
            $map['del'] = 0;
            if(empty($param['live_id'])){
                return Res::error('直播信息不存在');
            }
            //若选择销售
            $wx_unionid = [];
            if(isset($param['userid']) && $param['userid']){
                $wx_unionid = Db::table("xh_siyu_invitation_user")
                    ->where(['liveId'=>$param['live_id'],'sender'=>$param['userid']])
                    ->field('wx_unionid')
                    ->select()->toArray();
                if(count($wx_unionid)){
                    $wx_unionid = array_column($wx_unionid,'wx_unionid');
                     foreach ($wx_unionid as $k=>&$v){
                         $v = "'".$v."'";
                     }
                }else{
                    $data = [
                        'list' => [],
                        'total' => 0,
                    ];
                    return Res::ok($data);
                }
            }
            $pageNumber = !isset($param['pageNumber']) ? 1: (int) $param['pageNumber'];
            $pageSize = !isset($param['pageSize']) ? 100 : (int) $param['pageSize'];
            $collection = 'live_user_msg_'.$param['live_id'];
            $connection = MongoDBService::getInstance($collection)->getTable($collection);
            $conn = MongoDBService::getInstance($collection)->getTable($collection);
            if(count($wx_unionid)){
                $connection->where('wx_unionid','in',$wx_unionid);
                $conn->where('wx_unionid','in',$wx_unionid);
            }
            if(!empty($param['pageNumber']) && !empty($param['pageSize'])){
                $connection->limit($pageSize)->page($pageNumber);
            }
            $total = $conn->count();
            $rs = $connection->field('nickname,wx_avatarurl,content')->order('msg_seq','desc')->select();
            
            $data = [
                'list' => $rs,
                'total' => $total,
                'isSaler'
            ];
            return Res::ok($data);
    }   
    
    //设置课程销售状态
    public static function setCourseSellOut($param){
        if(!$param['liveId']){
            return Res::error('直播信息不存在');
        }
        if(!in_array($param['status'],[0,1])){
            return Res::error('状态错误');
        }
        if(!$param['goodsId']){
            return Res::error('未指定商品');
        }
        return Res::ok(['status'=>1]);
    }
    
    //获取播放信息
    public static function getPlayInfo($param){
        if(!$param['liveId']){
            Res::error('直播信息不存在');
        }
        $playinfo = DB::table('xh_siyu_live_manager')->alias('m')
            ->join(['xh_siyu_teacher'=> 't'], 'm.teacher_id = t.id')
            ->where("m.id",$param['liveId'])->field('m.id,m.push_file_name,m.conver,t.name')->find();
        
        
//        $playinfo = DB::table('xh_siyu_live_manager')->alias('m')
//            ->join(['xh_siyu_teacher'=> 't'], 'm.teacher_id = t.id')
//            ->where("m.id",$param['liveId'])->field('m.id,m.push_file_name,m.conver,t.name')->find();
        return Res::ok($playinfo);
    }
    
}
